package com.wanghaibo.vgashow;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.wanghaibo.vgashow.R;
import com.wanghaibo.vgashow.climatecontrol.AutoSwingFlapHandler;
import com.wanghaibo.vgashow.climatecontrol.ClimateControl;
import com.wanghaibo.vgashow.climatecontrol.SwingFlapBgView;
import com.wanghaibo.vgashow.climatecontrol.WindView;

import org.w3c.dom.Text;


public class MainActivity extends AppCompatActivity {

    private static String TAG="Climate_Main";
    private ClimateControl climateControl;

    private ConstraintLayout UiClimateControl, UiSeatHeat;//空调控制UI层（各种按钮）
    private ImageView climateControlBg;//空调控制背景图
    private ConstraintLayout windContainer;
    private WindView windView01, windView02, windView03, windView04;

    private Button btnOnOff, btnVentUp, btnVentMid, btnVentDown, btnAuto, btnAc, btnCycle, btnRear,btn_FanSpeedIncrease,btn_FanSpeedDecrease,btn_autoAc,btnSwingFlap;

    private AutoSwingFlapHandler autoSwingFlapHandler;

    private SwingFlapBgView swingFlapBgView;

    private TextView tv_FanSpeedLevel;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        climateControl = new ClimateControl(getApplicationContext());
        //绑定UI
        bindUI();

        //隐藏出风层
        if (!btnOnOff.isActivated()) {
            windContainer.setAlpha(0f);
            windContainer.setVisibility(View.GONE);
        } else {
            windContainer.setAlpha(1f);
            windContainer.setVisibility(View.VISIBLE);
        }

        //出风口方向变化监听器
        WindView.onWindXYChangedListener onWindXYChangedListener = new WindView.onWindXYChangedListener() {
            @Override
            public void onWindXYChangeStart(int windX, int windY) {
                //触摸调节出风口方向时隐藏按钮
                hideUiClimateControl();
            }

            @Override
            public void onWindXYConfirmed(WindView windView, int windX, int windY) {
                //抬起时取消隐藏按钮
                unhideUiClimateControl();
                //发送吹风口x、y位置
                switch (windView.getId()) {
                    case R.id.wind_view_01:
                        climateControl.setWindDirection(ClimateControl.VENT_01, windX, windY);
                        break;
                    case R.id.wind_view_02:
                        climateControl.setWindDirection(ClimateControl.VENT_02, windX, windY);
                        break;
                    case R.id.wind_view_03:
                        climateControl.setWindDirection(ClimateControl.VENT_03, windX, windY);
                        break;
                    case R.id.wind_view_04:
                        climateControl.setWindDirection(ClimateControl.VENT_04, windX, windY);
                        break;
                    default:
                        break;
                }
            }
        };
        windView01.setOnWindXYChangedListener(onWindXYChangedListener);
        windView02.setOnWindXYChangedListener(onWindXYChangedListener);
        windView03.setOnWindXYChangedListener(onWindXYChangedListener);
        windView04.setOnWindXYChangedListener(onWindXYChangedListener);

        //for auto AC
//        btn_autoAc.setOnClickListener(view -> {
//
//        });

        //处理按钮点击事件
        //空调开关
        btnOnOff.setOnClickListener(v -> {
            if (!btnOnOff.isActivated()) {
                //如果未开启，则开启空调
                if (climateControl.turnOn()) {
                    //Todo
                    Log.d(TAG,"powerOn");
//                    windView01.setWindXY(climateControl.getWindDirection(ClimateControl.VENT_01));

                    btnOnOff.setActivated(true);
//                    //打开内外循环
//                    btnCycle.setActivated(true);
//                    //打开三个出风口
//                    btnVentUp.setActivated(true);
//                    btnVentMid.setActivated(true);
//                    btnVentDown.setActivated(true);
//                    //打开A/C
//                    btnAc.setActivated(true);
//                    //打开后排空调
//                    btnRear.setActivated(true);
                    //显示出风层
                    unhideWindClimateControl();
                }
            } else {
                //否则关闭空调
                if (climateControl.turnOff()) {
                    Log.d(TAG,"powerOff");

                    btnOnOff.setActivated(false);
//                    //关闭内外循环
//                    btnCycle.setActivated(false);
//                    //关闭三个出风口
//                    btnVentUp.setActivated(false);
//                    btnVentMid.setActivated(false);
//                    btnVentDown.setActivated(false);
//                    //关闭A/C
//                    btnAc.setActivated(false);
//                    //关闭后排空调
//                    btnRear.setActivated(false);
                    //隐藏出风层
                    hideWindClimateControl();

                }
            }
        });
//        //自动空调
//        btnAuto.setOnClickListener(v -> {
//            if (!btnAuto.isActivated()) {
//                //如果未开启，则开启自动空调
//                if (climateControl.autoOn()) {
//                    btnAuto.setActivated(true);
//                }
//            } else {
//                //否则关闭自动空调
//                if (climateControl.autoOff()) {
//                    btnAuto.setActivated(false);
//                }
//            }
//
//        });
        //AC ON
        btnAc.setOnClickListener(v -> {
            if (!btnAc.isActivated()) {
                //如果未开启，则开启AC
                if (climateControl.acOn()) {
                    Log.d(TAG,"AC_On");
                    btnAc.setActivated(true);
                }
            } else {
                //否则关闭AC
                if (climateControl.acOff()) {
                    Log.d(TAG,"AC_Off");
                    btnAc.setActivated(false);
                }
            }
        });
        //内外循环
        btnCycle.setOnClickListener(v -> {
            // activated true:开启 false:关机
            // selected true:内循环 false:外循环
            if (btnCycle.isActivated()) {
                if (btnCycle.isSelected()) {
                    //如果是内循环，则开启外循环
                    if (climateControl.cycleExOn()) {
                        btnCycle.setSelected(false);
                    }
                } else {
                    //如果是外循环，则开启内循环
                    if (climateControl.cycleInOn()) {
                        btnCycle.setSelected(true);
                    }
                }
            }
        });
        //上出风口
        btnVentUp.setOnClickListener(v -> {
            if (!btnVentUp.isActivated()) {
                //如果未开启，则开启上出风口
                if (climateControl.ventUpOn()) {
                    btnVentUp.setActivated(true);
                }
            } else {
                //否则关闭上出风口
                if (climateControl.ventUpOff()) {
                    btnVentUp.setActivated(false);
                }
            }
        });
        //中出风口
        btnVentMid.setOnClickListener(v -> {
            if (!btnVentMid.isActivated()) {
                //如果未开启，则开启中出风口
                if (climateControl.ventMidOn()) {
                    btnVentMid.setActivated(true);
                }
            } else {
                //否则关闭中出风口
                if (climateControl.ventMidOff()) {
                    btnVentMid.setActivated(false);
                }
            }
        });
        //下出风口
        btnVentDown.setOnClickListener(v -> {
            if (!btnVentDown.isActivated()) {
                //如果未开启，则开启下出风口
                if (climateControl.ventDownOn()) {
                    btnVentDown.setActivated(true);
                }
            } else {
                //否则关闭下出风口
                if (climateControl.ventDownOff()) {
                    btnVentDown.setActivated(false);
                }
            }
        });

        //后排空调
        btnRear.setOnClickListener(v -> {
            if (!btnRear.isActivated()) {
                //如果未开启，则开启后排空调
                if (climateControl.rearOn()) {
                    btnRear.setActivated(true);
                }
            } else {
                //否则关闭后排空调
                if (climateControl.rearOff()) {
                    btnRear.setActivated(false);
                }
            }
        });

        //自动扫风
        btnSwingFlap.setOnClickListener(v -> {
            if (!btnSwingFlap.isActivated()) {
                //如果未开启，则开启自动扫风
                btnSwingFlap.setActivated(true);
                //初始化自动扫风线程
                autoSwingFlapHandler.startAutoSwingFlap();
                //开始播放视频并取消隐藏
                swingFlapBgView.startPlay();
                // Auto play
//                imgSwingFlapBg.setImageDrawable(apngDrawable);

//                if (climateControl.swingFlapOn()) {
//                    btnSwingFlap.setActivated(true);
//                    //开启自动扫风动画
//                    windView01.swingFlapStart(true, true, 8000, 5000);
//                    windView02.swingFlapStart(true, true, 8000, 5000);
//                    windView03.swingFlapStart(true, true, 8000, 5000);
//                    windView04.swingFlapStart(true, true, 8000, 5000);
//                }
            } else {
                //否则关闭自动扫风
                btnSwingFlap.setActivated(false);
                //结束扫风
                autoSwingFlapHandler.stopAutoSwingFlap();
                //停止播放视频并隐藏
                swingFlapBgView.stopPlay();
                // Auto play
//                imgSwingFlapBg.setImageDrawable(null);

//                if (climateControl.swingFlapOff()) {
//                    btnSwingFlap.setActivated(false);
//                    //停止自动扫风动画
//                    windView01.swingFlapStop();
//                    windView02.swingFlapStop();
//                    windView03.swingFlapStop();
//                    windView04.swingFlapStop();
//                }
            }
        });

        //风速减小
        btn_FanSpeedDecrease.setOnClickListener(v ->{
            climateControl.FanSpeedDecrease();
        });
        //风速增加
        btn_FanSpeedIncrease.setOnClickListener(v ->{

        });

        //风速显示
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv_FanSpeedLevel.setText(""+climateControl.FanSpeedLevel);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void hideWindClimateControl() {
        //隐藏windContainer
        ObjectAnimator animator = ObjectAnimator.ofFloat(windContainer, "alpha", windContainer.getAlpha(), 0.0f)
                .setDuration(400);
        animator.setAutoCancel(true);
        animator.start();
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                windContainer.setVisibility(View.GONE);
                super.onAnimationEnd(animation);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void unhideWindClimateControl() {
        //取消隐藏windContainer
        windContainer.setVisibility(View.VISIBLE);
        ObjectAnimator animator = ObjectAnimator.ofFloat(windContainer, "alpha", windContainer.getAlpha(), 1.0f)
                .setDuration(200);
        animator.setAutoCancel(true);
        animator.start();
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void hideUiClimateControl() {
        //触摸时隐藏按钮
        ObjectAnimator animator1 = ObjectAnimator.ofFloat(UiClimateControl, "alpha", UiClimateControl.getAlpha(), 0.0f)
                .setDuration(400);
        animator1.setAutoCancel(true);
        animator1.start();
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void unhideUiClimateControl() {
        //抬起时取消隐藏按钮
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(UiClimateControl, "alpha", UiClimateControl.getAlpha(), 1.0f)
                .setDuration(200);
        animator2.setAutoCancel(true);
        animator2.start();
    }


    private void bindUI() {
        //绑定UI
        UiClimateControl = (ConstraintLayout) findViewById(R.id.ui_climate_control);
        UiSeatHeat = (ConstraintLayout) findViewById(R.id.ui_seat_heat);
        climateControlBg = (ImageView) findViewById(R.id.climate_control_background);
        windContainer = (ConstraintLayout) findViewById(R.id.wind_container);
        windView01 = (WindView) findViewById(R.id.wind_view_01);
        windView02 = (WindView) findViewById(R.id.wind_view_02);
        windView03 = (WindView) findViewById(R.id.wind_view_03);
        windView04 = (WindView) findViewById(R.id.wind_view_04);
        btnOnOff = (Button) findViewById(R.id.btn_on_off);
        btnVentUp = (Button) findViewById(R.id.btn_vent_up);
        btnVentMid = (Button) findViewById(R.id.btn_vent_mid);
        btnVentDown = (Button) findViewById(R.id.btn_vent_down);
        btnAuto = (Button) findViewById(R.id.btn_auto);
        btnAc = (Button) findViewById(R.id.btn_ac);
        btnCycle = (Button) findViewById(R.id.btn_cycle);
        btnRear = (Button) findViewById(R.id.btn_rear);

        //自动扫风
        btnSwingFlap = (Button) findViewById(R.id.btn_swing_flap);
        autoSwingFlapHandler = new AutoSwingFlapHandler(MainActivity.this,
                windView01, windView02, windView03, windView04);
        //视频背景
        swingFlapBgView = (SwingFlapBgView) findViewById(R.id.video_view);
        swingFlapBgView.init(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sea_wave), R.raw.sea_wave_music);


        //风扇调节
        btn_FanSpeedDecrease = (Button)findViewById(R.id.btn_FanSpeedDecrease);
        btn_FanSpeedIncrease = (Button)findViewById(R.id.btn_FanSpeedIncrease);
        tv_FanSpeedLevel = (TextView)findViewById(R.id.tv_fan_speed);

        //For auto AC
//        btn_autoAc=(Button)findViewById(R.id.btn_autoAC);


    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        //防止锁屏或者弹出的时候，音乐在播放
        swingFlapBgView.stopPlay();
        // Auto play
//        imgSwingFlapBg.setImageDrawable(null);
        //停止扫风
        autoSwingFlapHandler.stopAutoSwingFlap();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        swingFlapBgView.releaseResource();
    }

    public void switchToClimateControl(View view) {
        UiClimateControl.setVisibility(View.VISIBLE);
        UiSeatHeat.setVisibility(View.GONE);
        climateControlBg.setVisibility(View.VISIBLE);
        windContainer.setVisibility(View.VISIBLE);

    }

    public void switchToSeatHeat(View view) {
        UiClimateControl.setVisibility(View.GONE);
        UiSeatHeat.setVisibility(View.VISIBLE);
        climateControlBg.setVisibility(View.GONE);
        windContainer.setVisibility(View.GONE);
    }

    public void exitClimateControl(View view) {
//        Intent home = new Intent(Intent.ACTION_MAIN);
//        home.addCategory(Intent.CATEGORY_HOME);
//        startActivity(home);
        this.finish();
    }
}